# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time
import datetime
from openerp.report import report_sxw


from crea8s_training1_demo.practice_khtn import crea8s_training1_demo_class # okokok
# from crea8s_training1_demo import crea8s_training1_demo_class # nonono


report_type = []

class report_crea8s_pos_phongnd(report_sxw.rml_parse):
    def __init__(self, cr, uid, name, context=None):
        super(report_crea8s_pos_phongnd, self).__init__(cr, uid, name, context=context)
        self.localcontext.update({
            'time': time,
            'get_order': self.get_order,
            'group_order_line': self.group_order_line,
            
        })
    
    def get_order(self, session_id):
        result     = []
        pos_order_obj = self.pool.get('pos.order')
        order_ids = pos_order_obj.search(self.cr, self.uid, [('session_id', '=', session_id)], order='date_order DESC', limit=10)
        nuCount = 0
        for record in pos_order_obj.browse(self.cr, self.uid, order_ids):
            nuCount += 1
            dct_result = {}
            
            dct_result['line_no'] = nuCount    
            print record, '  gia tri dang coi' 
            strFM = '%A %B %d %Y %H:%M:%S'
            # datetime.strptime( record.date_order.strftime(strFM)
            
            
#             asd = new crea8s_training1_demo_class() 
            objHuongdan = self.pool.get('crea8s.training1.demo.class')

            dct_result.update({'order_date_formated':  objHuongdan.process_date_title(record.date_order)})
            
            dct_result.update({'order_date': objHuongdan.process_date_title2(record.date_order)})
            dct_result.update({'order_ref': record.name})
            dct_result.update({'session_id': record.session_id})
            dct_result.update({'order_line': self.group_order_line(record.lines)})
         #   record.amount_total
            dct_result.update({'amount_total': record.amount_total})
            
            print 'get_order => order_line: ' + str(dct_result['order_line'])
            result.append(dct_result)
            
        return result
#         return {'arrDetails': result, 'total': 123}

#     def process_date_title(self, date_or):
#         temp = datetime.datetime(int(date_or[:4]), int(date_or[5:7]), int(date_or[8:10]), int(date_or[11:13]), int(date_or[14:16]), int(date_or[17:19]))
# #         temp += timedelta(hours=7)
#         result = time.strftime('%a %b %d %Y %H:%M:%S',time.strptime(str(temp), '%Y-%m-%d %H:%M:%S'))
#         
#         return result
# 
#     def process_date_title2(self, date_or):
#         temp = datetime.datetime(int(date_or[:4]), int(date_or[5:7]), int(date_or[8:10]), int(date_or[11:13]), int(date_or[14:16]), int(date_or[17:19]))
# #         temp += timedelta(hours=7)
#         result = time.strftime('%d-%m-%Y %H:%M:%S',time.strptime(str(temp), '%Y-%m-%d %H:%M:%S'))
#         
#         return result
    
    def group_order_line(self, brProducts):
        
        # follow Tri: lst_uniq = list(set(x.product_id.name for x in lst_product))
        arrResult = {}
        pos_order_obj = self.pool.get('pos.order.line')
#         objOrderDetail = pos_order_obj.search(self.cr, self.uid, [('id', '=', order_id)], order='id ASC')
#         for record in objOrderDetail.browse(self.cr, self.uid, arrIDs):
        nuCount = 0
        for record in brProducts:
            nuCount += 1
            arrProduct = {}   
            pro_id = record.product_id.id         
            if arrResult.has_key(pro_id):
                arrProduct_old = arrResult[pro_id]
                arrProduct.update({'qty': record.qty + arrProduct_old['qty']})
                arrProduct.update({'price_subtotal_incl': record.price_subtotal_incl + arrProduct_old['price_subtotal_incl']})
                
            else:
                arrProduct.update({'qty': record.qty})
                arrProduct.update({'price_subtotal_incl': record.price_subtotal_incl})
            
            arrProduct.update({'line_no': record.name})
            arrProduct.update({'product_id': pro_id})
            arrProduct.update({'product_name': record.product_id.name})
            arrResult[pro_id] = arrProduct
#             arrResult.append(dct_arrResult)

        arrResult2 = []
        for index, item in arrResult.items():  # enumerate for ARRRAY!!!
             arrResult2.append(arrResult[index])
             
#         print 'group_order_line: ' + str(arrResult)
#         print 'group_order_line-arrResult2222: ' + str(arrResult2)
        return arrResult2
    
report_sxw.report_sxw('report.crea8s.pos.order.phongnd', 'pos.session', 'addons/crea8s_pos_report-phongnd/report/session_order_10.rml', parser=report_crea8s_pos_phongnd, header=False)




